package fr.adfm;


import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import webService.entities.Compte;
import webService.entities.Transaction;
import webService.implementation.WSPaiement;
import webService.util.CompteDTO;
import webService.util.EtatTransaction;
import webService.util.TestMail;
import webService.util.TransactionDTO;

/**
 * Servlet implementation class SaisieCarte
 */
@WebServlet(urlPatterns={"/enter"})
public class SaisieCarte extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public SaisieCarte() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String nom = request.getParameter("nom");
		String num = request.getParameter("num");
		String crypt = request.getParameter("crypt");
		
		String uuid = request.getParameter("uuid");
		
		CompteDTO compte=  WSPaiement.comptes.get(nom);
		if(compte.getNomDeCompte().equals(nom) &&
				compte.getNumero().equals(num) &&
				compte.getCryptogramme().equals(crypt) 
				)
		{
			//envoie du code et l'enregistrer
			TransactionDTO transactionDTO = WSPaiement.transactions.get(uuid);
			if(transactionDTO.getSomme() < compte.getSolde())
			{
				String codeGen = UUID.randomUUID().toString();
				System.out.println("Simulation envoie code sur email" + codeGen);
				TestMail testMail = new TestMail();
				testMail.send("guion.alexandre@live.fr", codeGen);
				transactionDTO.setCode(codeGen);
				WSPaiement.transactions.put(uuid, transactionDTO);
				//envoie
				request.setAttribute("erreur", "");
				request.getRequestDispatcher("code.jsp?uuid=" + uuid).forward(request, response);
			}
			else
			{
				transactionDTO.setEtatTransaction(EtatTransaction.REFUSE);
				WSPaiement.transactions.put(uuid, transactionDTO);
				response.sendRedirect(transactionDTO.getUrlRetour());
			}
			
		}
		else
		{
			request.setAttribute("erreur", "Carte inconnue");
			request.getRequestDispatcher("saisieCarte.jsp?uuid=" + uuid).forward(request, response);
		}
		
		
	}

}
